<template>
  <div class="profit-loss-report">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="15" animated />
    </div>

    <template v-else>
      <!-- 顶部卡片 - 关键指标 -->
      <div class="metric-cards">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="总收入" 
              :value="formatCurrency(overview.totalRevenue)" 
              :growth="overview.revenueGrowth" 
              :previous-value="formatCurrency(previousPeriod.totalRevenue)"
              icon="Wallet"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="总成本" 
              :value="formatCurrency(overview.totalCost)" 
              :growth="overview.costGrowth" 
              :previous-value="formatCurrency(previousPeriod.totalCost)"
              icon="Money"
              :inverse-growth="true"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="总利润" 
              :value="formatCurrency(overview.totalProfit)" 
              :growth="overview.profitGrowth" 
              :previous-value="formatCurrency(previousPeriod.totalProfit)"
              icon="Money"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="利润率" 
              :value="`${formatNumber(overview.profitMargin)}%`" 
              :growth="overview.profitMarginGrowth" 
              :previous-value="`${formatNumber(previousPeriod.profitMargin)}%`"
              icon="DataAnalysis"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 报表控制面板 -->
      <el-card class="control-panel" shadow="hover">
        <div class="control-panel-content">
          <div class="panel-section">
            <span class="section-label">报表周期:</span>
            <el-radio-group v-model="periodType" size="small" @change="handlePeriodChange">
              <el-radio-button :value="'daily'">日报表</el-radio-button>
              <el-radio-button :value="'weekly'">周报表</el-radio-button>
              <el-radio-button :value="'monthly'">月报表</el-radio-button>
              <el-radio-button :value="'quarterly'">季度报表</el-radio-button>
              <el-radio-button :value="'yearly'">年度报表</el-radio-button>
            </el-radio-group>
          </div>
          
          <div class="panel-section">
            <span class="section-label">对比方式:</span>
            <el-radio-group v-model="comparisonType" size="small" @change="handleComparisonChange">
              <el-radio-button :value="'previous'">环比</el-radio-button>
              <el-radio-button :value="'samePeriodLastYear'">同比</el-radio-button>
              <el-radio-button :value="'none'">不对比</el-radio-button>
            </el-radio-group>
          </div>
          
          <div class="panel-actions">
            <el-button type="primary" size="small" @click="printReport">
              <el-icon><Printer /></el-icon> 打印报表
            </el-button>
            <el-button type="success" size="small" @click="exportExcel">
              <el-icon><Download /></el-icon> 导出Excel
            </el-button>
            <el-button size="small" @click="refreshData">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 利润趋势图 -->
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">利润趋势分析</span>
            <div class="card-actions">
              <el-radio-group v-model="trendMetric" size="small" @change="updateTrendChart">
                <el-radio-button :value="'revenue'">收入</el-radio-button>
                <el-radio-button :value="'cost'">成本</el-radio-button>
                <el-radio-button :value="'profit'">利润</el-radio-button>
                <el-radio-button :value="'all'">全部</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        <div class="chart-container" ref="profitTrendChartRef"></div>
      </el-card>

      <!-- 收入和成本占比图 -->
      <el-row :gutter="20" class="composition-charts">
        <el-col :xs="24" :md="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">收入结构分析</span>
                <el-tooltip content="显示收入来源的构成比例">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="revenueCompositionChartRef"></div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :md="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title">成本结构分析</span>
                <el-tooltip content="显示成本构成的比例分布">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container" ref="costCompositionChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 损益表详情 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">损益表详情</span>
            <el-tooltip content="展示详细的收入、成本和利润明细">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        
        <!-- 表格切换器 -->
        <div class="table-view-controls">
          <el-radio-group v-model="tableView" size="small">
            <el-radio-button :value="'standard'">标准视图</el-radio-button>
            <el-radio-button :value="'detailed'">详细视图</el-radio-button>
            <el-radio-button :value="'comparison'">对比视图</el-radio-button>
          </el-radio-group>
        </div>
        
        <!-- 标准视图 -->
        <el-table 
          v-if="tableView === 'standard'" 
          :data="filteredProfitLossDetails" 
          stripe 
          border
          style="width: 100%"
          :span-method="objectSpanMethod"
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="category" label="项目" min-width="180" />
          <el-table-column prop="subcategory" label="子项目" min-width="180" />
          <el-table-column prop="amount" label="金额" min-width="120">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.amount)">
                {{ formatCurrency(Math.abs(scope.row.amount)) }}
                <span v-if="scope.row.amount < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="小计" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.isSubtotal" :class="getAmountClass(scope.row.total)">
                {{ formatCurrency(Math.abs(scope.row.total)) }}
                <span v-if="scope.row.total < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ratio" label="占比" min-width="100">
            <template #default="scope">
              <span v-if="scope.row.ratio !== undefined">{{ scope.row.ratio }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="说明" min-width="200" />
        </el-table>
        
        <!-- 详细视图 -->
        <el-table 
          v-if="tableView === 'detailed'" 
          :data="detailedProfitLossDetails" 
          stripe 
          border
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="name" label="项目" min-width="250" />
          <el-table-column prop="amount" label="金额" min-width="150">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.amount)">
                {{ formatCurrency(Math.abs(scope.row.amount)) }}
                <span v-if="scope.row.amount < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="ratio" label="占比" min-width="100">
            <template #default="scope">
              <span v-if="scope.row.ratio !== undefined">{{ scope.row.ratio }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="growth" label="增长率" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.growth !== undefined" :class="getGrowthClass(scope.row.growth, scope.row.isInverseGrowth)">
                {{ scope.row.growth >= 0 ? '+' : '' }}{{ scope.row.growth }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="comment" label="说明" min-width="200" />
        </el-table>
        
        <!-- 对比视图 -->
        <el-table 
          v-if="tableView === 'comparison'" 
          :data="comparisonProfitLossDetails" 
          stripe 
          border
          style="width: 100%"
          :row-class-name="getRowClassName"
        >
          <el-table-column prop="name" label="项目" min-width="180" />
          <el-table-column prop="currentAmount" label="本期金额" min-width="150">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.currentAmount)">
                {{ formatCurrency(Math.abs(scope.row.currentAmount)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="previousAmount" :label="comparisonLabel" min-width="150">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.previousAmount)">
                {{ formatCurrency(Math.abs(scope.row.previousAmount)) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="difference" label="差额" min-width="150">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.difference)">
                {{ formatCurrency(Math.abs(scope.row.difference)) }}
                <span v-if="scope.row.difference < 0">(-)</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="growth" label="增长率" min-width="120">
            <template #default="scope">
              <span :class="getGrowthClass(scope.row.growth, scope.row.isInverseGrowth)">
                {{ scope.row.growth >= 0 ? '+' : '' }}{{ scope.row.growth }}%
              </span>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 利润汇总 -->
        <div class="summary-section">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8">
              <div class="summary-item">
                <span class="summary-label">毛利润:</span>
                <span class="summary-value">{{ formatCurrency(summary.grossProfit) }}</span>
                <span class="summary-percentage">({{ summary.grossProfitMargin }}%)</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8">
              <div class="summary-item">
                <span class="summary-label">营业利润:</span>
                <span class="summary-value">{{ formatCurrency(summary.operatingProfit) }}</span>
                <span class="summary-percentage">({{ summary.operatingProfitMargin }}%)</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8">
              <div class="summary-item">
                <span class="summary-label">净利润:</span>
                <span class="summary-value">{{ formatCurrency(summary.netProfit) }}</span>
                <span class="summary-percentage">({{ summary.netProfitMargin }}%)</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
      
      <!-- 备注说明 -->
      <el-card class="note-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">报表说明</span>
          </div>
        </template>
        <div class="note-content">
          <p><strong>报表周期:</strong> {{ getPeriodTypeLabel(periodType) }}</p>
          <p><strong>统计时间:</strong> {{ formatDate(dateRange[0]) }} 至 {{ formatDate(dateRange[1]) }}</p>
          <p><strong>对比方式:</strong> {{ getComparisonTypeLabel(comparisonType) }}</p>
          <p><strong>数据来源:</strong> 订单系统、库存系统、财务系统</p>
          <p><strong>统计说明:</strong> 本报表仅统计已完成订单，不包含已取消或退款订单。费用数据来自手动录入的费用记录。</p>
        </div>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { 
  Printer, Download, Refresh, InfoFilled,
  Money, Wallet, DataAnalysis
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts/core';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import {
  TitleComponent, TooltipComponent, GridComponent,
  LegendComponent, DataZoomComponent, ToolboxComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { formatCurrency, formatNumber, formatDate } from '@/utils/formatters';
import { exportToExcel, printContent } from '@/utils/exportUtils';
import MetricCard from './common/MetricCard.vue';
import reportApi from '@/api/reports';

// 注册ECharts组件
echarts.use([
  BarChart, LineChart, PieChart,
  TitleComponent, TooltipComponent, GridComponent,
  LegendComponent, DataZoomComponent, ToolboxComponent,
  CanvasRenderer
]);

const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['refresh']);

// 状态变量
const periodType = ref('monthly');
const comparisonType = ref('previous');
const trendMetric = ref('all');
const tableView = ref('standard');

// 图表引用
const profitTrendChartRef = ref(null);
const revenueCompositionChartRef = ref(null);
const costCompositionChartRef = ref(null);

// 图表实例
let profitTrendChartInstance = null;
let revenueCompositionChartInstance = null;
let costCompositionChartInstance = null;

// 计算属性 - 从报表数据中提取需要的数据
const overview = computed(() => props.reportData.overview || {});
const previousPeriod = computed(() => props.reportData.previousPeriod || {});
const details = computed(() => props.reportData.details || []);
const revenueComposition = computed(() => props.reportData.revenueComposition || []);
const costComposition = computed(() => props.reportData.costComposition || []);
const profitTrend = computed(() => props.reportData.profitTrend || []);
const summary = computed(() => props.reportData.summary || {});

// 根据表格类型过滤数据
const filteredProfitLossDetails = computed(() => {
  return details.value;
});

// 树形详细视图数据
const detailedProfitLossDetails = computed(() => {
  // 将平面数据转换为树形结构
  if (!details.value || details.value.length === 0) return [];
  
  const result = [];
  const categoryMap = {};
  
  details.value.forEach(item => {
    // 如果是小计行，不处理
    if (item.isSubtotal) return;
    
    // 如果分类不存在，创建分类节点
    if (!categoryMap[item.category]) {
      const categoryNode = {
        id: `category-${item.category}`,
        name: item.category,
        amount: 0,
        children: [],
        isCategory: true
      };
      
      result.push(categoryNode);
      categoryMap[item.category] = categoryNode;
    }
    
    // 创建子项目节点
    const subItemNode = {
      id: `subitem-${item.category}-${item.subcategory}`,
      name: item.subcategory,
      amount: item.amount,
      ratio: item.ratio,
      growth: item.growth,
      comment: item.comment
    };
    
    // 将子项目添加到分类节点
    categoryMap[item.category].children.push(subItemNode);
    
    // 累加分类金额
    categoryMap[item.category].amount += item.amount;
  });
  
  // 计算分类占比
  const totalAmount = result.reduce((sum, item) => sum + Math.abs(item.amount), 0);
  
  result.forEach(category => {
    category.ratio = totalAmount === 0 ? 0 : 
      Math.round((Math.abs(category.amount) / totalAmount) * 100 * 100) / 100;
  });
  
  return result;
});

// 对比视图数据
const comparisonProfitLossDetails = computed(() => {
  // 当没有对比数据时返回空数组
  if (comparisonType.value === 'none' || !details.value || details.value.length === 0) return [];
  
  // 提取主要类别的当前和对比数据
  const result = [];
  const categories = [...new Set(details.value.map(item => item.category))];
  
  categories.forEach(category => {
    const categoryItems = details.value.filter(item => item.category === category);
    
    // 获取当前期间金额（合计）
    const currentAmount = categoryItems.reduce((sum, item) => {
      return item.isSubtotal ? sum + item.total : sum;
    }, 0);
    
    // 获取上期金额（如果有的话）
    const previousAmount = (props.reportData.previousDetails || [])
      .filter(item => item.category === category && item.isSubtotal)
      .reduce((sum, item) => sum + item.total, 0);
    
    // 计算差额和增长率
    const difference = currentAmount - previousAmount;
    const growth = previousAmount === 0 ? 0 : 
      Math.round((difference / previousAmount) * 100 * 100) / 100;
    
    // 添加到结果数组
    result.push({
      name: category,
      currentAmount,
      previousAmount,
      difference,
      growth,
      isInverseGrowth: category.includes('成本') || category.includes('费用')
    });
  });
  
  return result;
});

// 对比标签
const comparisonLabel = computed(() => {
  return comparisonType.value === 'previous' ? '上期金额' : 
    comparisonType.value === 'samePeriodLastYear' ? '去年同期' : '对比金额';
});

// 处理周期类型变更
const handlePeriodChange = () => {
  refreshData();
};

// 处理对比方式变更
const handleComparisonChange = () => {
  refreshData();
};

// 刷新数据
const refreshData = () => {
  emit('refresh', { periodType: periodType.value, comparisonType: comparisonType.value });
};

// 打印报表
const printReport = () => {
  // 构建打印内容
  const printTitle = `哈喽啤鲜生 - ${getPeriodTypeLabel(periodType.value)}损益表`;
  const dateRangeText = `${formatDate(props.dateRange[0])} 至 ${formatDate(props.dateRange[1])}`;
  
  let printContent = `
    <div class="print-header">
      <h1>${printTitle}</h1>
      <p>${dateRangeText}</p>
    </div>
  `;
  
  // 添加报表详情表格
  printContent += `
    <table class="print-table">
      <thead>
        <tr>
          <th>项目</th>
          <th>子项目</th>
          <th>金额</th>
          <th>小计</th>
          <th>占比</th>
          <th>说明</th>
        </tr>
      </thead>
      <tbody>
  `;
  
  // 添加表格行
  details.value.forEach(item => {
    printContent += `
      <tr>
        <td>${item.category}</td>
        <td>${item.subcategory}</td>
        <td>${formatCurrency(Math.abs(item.amount))}${item.amount < 0 ? ' (-)' : ''}</td>
        <td>${item.isSubtotal ? formatCurrency(Math.abs(item.total)) + (item.total < 0 ? ' (-)' : '') : ''}</td>
        <td>${item.ratio !== undefined ? item.ratio + '%' : ''}</td>
        <td>${item.comment || ''}</td>
      </tr>
    `;
  });
  
  printContent += `
      </tbody>
    </table>
  `;
  
  // 添加汇总信息
  printContent += `
    <div class="print-summary">
      <p><strong>毛利润:</strong> ${formatCurrency(summary.value.grossProfit)} (${summary.value.grossProfitMargin}%)</p>
      <p><strong>营业利润:</strong> ${formatCurrency(summary.value.operatingProfit)} (${summary.value.operatingProfitMargin}%)</p>
      <p><strong>净利润:</strong> ${formatCurrency(summary.value.netProfit)} (${summary.value.netProfitMargin}%)</p>
    </div>
  `;
  
  // 调用打印功能
  printContent(printContent, printTitle);
};

// 导出Excel
const exportExcel = () => {
  // 构建Excel数据
  const excelData = details.value.map(item => ({
    '项目': item.category,
    '子项目': item.subcategory,
    '金额': item.amount,
    '小计': item.isSubtotal ? item.total : '',
    '占比': item.ratio !== undefined ? item.ratio + '%' : '',
    '说明': item.comment || ''
  }));
  
  // 文件名
  const fileName = `哈喽啤鲜生_${getPeriodTypeLabel(periodType.value)}损益表_${formatDate(props.dateRange[0])}_${formatDate(props.dateRange[1])}.xlsx`;
  
  // 导出Excel
  exportToExcel(excelData, fileName, '损益表');
};

// 更新趋势图表
const updateTrendChart = () => {
  if (!profitTrendChartInstance || !profitTrend.value || profitTrend.value.length === 0) return;
  
  const xAxisData = profitTrend.value.map(item => item.date);
  const series = [];
  
  // 根据选择的指标添加系列
  if (trendMetric.value === 'revenue' || trendMetric.value === 'all') {
    series.push({
      name: '收入',
      type: 'bar',
      data: profitTrend.value.map(item => item.revenue),
      itemStyle: {
        color: '#67C23A'
      }
    });
  }
  
  if (trendMetric.value === 'cost' || trendMetric.value === 'all') {
    series.push({
      name: '成本',
      type: 'bar',
      data: profitTrend.value.map(item => item.cost),
      itemStyle: {
        color: '#F56C6C'
      }
    });
  }
  
  if (trendMetric.value === 'profit' || trendMetric.value === 'all') {
    series.push({
      name: '利润',
      type: 'line',
      yAxisIndex: 1,
      data: profitTrend.value.map(item => item.profit),
      lineStyle: {
        width: 3
      },
      itemStyle: {
        color: '#409EFF'
      }
    });
  }
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = `${params[0].axisValue}<br/>`;
        
        params.forEach(param => {
          result += `${param.marker}${param.seriesName}: ${formatCurrency(param.value)}<br/>`;
        });
        
        return result;
      }
    },
    legend: {
      data: series.map(item => item.name)
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        axisLabel: {
          formatter: value => formatCurrency(value, '¥', 0)
        }
      },
      {
        type: 'value',
        name: '利润',
        axisLabel: {
          formatter: value => formatCurrency(value, '¥', 0)
        }
      }
    ],
    series: series
  };
  
  profitTrendChartInstance.setOption(option);
};

// 初始化收入构成图表
const initRevenueCompositionChart = () => {
  if (!revenueCompositionChartRef.value || !revenueComposition.value || revenueComposition.value.length === 0) return;
  
  revenueCompositionChartInstance = echarts.init(revenueCompositionChartRef.value);
  
  // 设置饼图选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: revenueComposition.value.map(item => item.name)
    },
    series: [
      {
        name: '收入来源',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: revenueComposition.value.map(item => ({
          name: item.name,
          value: item.value
        }))
      }
    ]
  };
  
  revenueCompositionChartInstance.setOption(option);
};

// 初始化成本构成图表
const initCostCompositionChart = () => {
  if (!costCompositionChartRef.value || !costComposition.value || costComposition.value.length === 0) return;
  
  costCompositionChartInstance = echarts.init(costCompositionChartRef.value);
  
  // 设置饼图选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: costComposition.value.map(item => item.name)
    },
    series: [
      {
        name: '成本构成',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: costComposition.value.map(item => ({
          name: item.name,
          value: item.value
        }))
      }
    ]
  };
  
  costCompositionChartInstance.setOption(option);
};

// 初始化所有图表
const initCharts = () => {
  // 清除旧的图表实例
  if (profitTrendChartInstance) {
    profitTrendChartInstance.dispose();
  }
  
  if (revenueCompositionChartInstance) {
    revenueCompositionChartInstance.dispose();
  }
  
  if (costCompositionChartInstance) {
    costCompositionChartInstance.dispose();
  }
  
  // 创建新的图表实例
  nextTick(() => {
    // 利润趋势图
    if (profitTrendChartRef.value) {
      profitTrendChartInstance = echarts.init(profitTrendChartRef.value);
      updateTrendChart();
    }
    
    // 收入构成图
    initRevenueCompositionChart();
    
    // 成本构成图
    initCostCompositionChart();
  });
};

// 获取周期类型标签
const getPeriodTypeLabel = (type) => {
  const labels = {
    daily: '日',
    weekly: '周',
    monthly: '月',
    quarterly: '季度',
    yearly: '年度'
  };
  
  return labels[type] || type;
};

// 获取对比类型标签
const getComparisonTypeLabel = (type) => {
  const labels = {
    previous: '环比',
    samePeriodLastYear: '同比',
    none: '不对比'
  };
  
  return labels[type] || type;
};

// 获取金额样式
const getAmountClass = (amount) => {
  if (amount === undefined || amount === null) return '';
  
  return {
    'negative-amount': amount < 0,
    'positive-amount': amount > 0
  };
};

// 获取增长率样式
const getGrowthClass = (growth, isInverse = false) => {
  if (growth === undefined || growth === null) return '';
  
  if (isInverse) {
    return {
      'negative-growth': growth > 0,
      'positive-growth': growth < 0
    };
  }
  
  return {
    'positive-growth': growth > 0,
    'negative-growth': growth < 0
  };
};

// 获取行样式
const getRowClassName = ({ row }) => {
  if (row.isCategory || row.isSubtotal) return 'subtotal-row';
  return '';
};

// 表格合并单元格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 对于小计行，只显示"小计"列和对应的值
  if (row.isSubtotal) {
    if (columnIndex === 0) {
      return [1, 2]; // 合并前两列
    } else if (columnIndex === 1) {
      return [0, 0]; // 隐藏第二列
    } else if (columnIndex === 2) {
      return [0, 0]; // 隐藏第三列
    }
  }
  
  return undefined;
};

// 监听数据变化，更新图表
watch(() => props.reportData, () => {
  initCharts();
}, { deep: true });

// 组件挂载时初始化
onMounted(() => {
  // 初始化图表
  initCharts();
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    profitTrendChartInstance && profitTrendChartInstance.resize();
    revenueCompositionChartInstance && revenueCompositionChartInstance.resize();
    costCompositionChartInstance && costCompositionChartInstance.resize();
  });
});

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', () => {
    profitTrendChartInstance && profitTrendChartInstance.resize();
    revenueCompositionChartInstance && revenueCompositionChartInstance.resize();
    costCompositionChartInstance && costCompositionChartInstance.resize();
  });
  
  // 销毁图表实例
  profitTrendChartInstance && profitTrendChartInstance.dispose();
  revenueCompositionChartInstance && revenueCompositionChartInstance.dispose();
  costCompositionChartInstance && costCompositionChartInstance.dispose();
});
</script>

<style scoped>
.profit-loss-report {
  margin-bottom: 30px;
}

.loading-container {
  min-height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 控制面板样式 */
.control-panel {
  margin-bottom: 20px;
}

.control-panel-content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.panel-section {
  margin: 10px 20px 10px 0;
  display: flex;
  align-items: center;
}

.section-label {
  margin-right: 10px;
  font-weight: bold;
}

.panel-actions {
  margin: 10px 0;
}

/* 图表卡片样式 */
.chart-card {
  margin-bottom: 20px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.card-actions {
  display: flex;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.composition-charts {
  margin-bottom: 20px;
}

/* 表格样式 */
.table-card {
  margin-bottom: 20px;
}

.table-view-controls {
  margin-bottom: 15px;
}

.subtotal-row {
  background-color: #f5f7fa !important;
  font-weight: bold;
}

.negative-amount {
  color: #F56C6C;
}

.positive-amount {
  color: #67C23A;
}

.negative-growth {
  color: #F56C6C;
}

.positive-growth {
  color: #67C23A;
}

/* 汇总部分样式 */
.summary-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
}

.summary-item {
  margin-bottom: 10px;
  font-size: 14px;
}

.summary-label {
  font-weight: bold;
  margin-right: 8px;
}

.summary-value {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.summary-percentage {
  margin-left: 8px;
  color: #909399;
}

/* 备注卡片样式 */
.note-card {
  margin-bottom: 20px;
}

.note-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .control-panel-content {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .panel-section {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 280px;
  }
}
</style> 